﻿#include "GLLInc.h"
#include "GLLDebug.h"

namespace GLL
{
	namespace Debug
	{
		//锁一下，否则会乱掉
		static GLL_Mutex mut;
#define LOCK GLL_Mutex::scoped_lock loc(mut)

		///是否需要将调试信息输出至文件
		static bool debug_Log_File = true;
		static const int MAX_OUTPUT_CHAR_NUM = 10240;
		static char Out[MAX_OUTPUT_CHAR_NUM] = {0};
		static const char* LogFileName = "Trace.Output.Log";

		void Log2File(const char* msg)
		{
			static FILE* file = 0;
			if(!file) fopen_s(&file, LogFileName, "w");
			if(file){
				int len = strlen(msg);
				fwrite(msg, len, 1, file);
				fflush(file);
			}
		}

		void Log2Console( const utf8* _fomat_str, ... )
		{
			LOCK;
			String fomat_str = Utf82Str(_fomat_str);
			va_list args;
			va_start(args, fomat_str);
			_vsnprintf_s(Out, MAX_OUTPUT_CHAR_NUM, fomat_str.c_str(), args);
			va_end(args);
			OutputDebugString(Out);
			if(debug_Log_File)Log2File(Out);
		}

		void Log2Console( const char* _fomat_str, ... )
		{
			LOCK;
			va_list args;
			va_start(args, _fomat_str);
			_vsnprintf_s(Out, MAX_OUTPUT_CHAR_NUM, _fomat_str, args);
			va_end(args);
			OutputDebugString(Out);
			if(debug_Log_File)Log2File(Out);
		}

		//-----------------------------------------------------------------------------
		WndPopup osPopup;

		void WndPopup::Show( const char* Msg, bool ExitGame)
		{
			StringStream strstr;
			strstr<<Msg;
			DoPopup(ExitGame, strstr);
		}

		void WndPopup::Show( const char* Message, const char* file, long line, bool ExitGame)
		{
			StringStream strstr;
			strstr<<Message;
			if(*file){
				strstr <<" / "<<file;
			}
			if(line){
				strstr<<"("<<line<<")";
			}

			DoPopup(ExitGame, strstr);
		}

		void WndPopup::Show( const String& msg, const char* cpp_file_name/*=""*/, long cpp_file_line/*=0*/, bool ExitGame /*= true */ )
		{
			Show(msg.c_str(), cpp_file_name, cpp_file_line, ExitGame);
		}

		void WndPopup::Show( StringStream& strm, const char* cpp_file_name/*=""*/, long cpp_file_line/*=0*/, bool ExitGame /*= true */ )
		{
			String msg(strm.str());
			Show(msg.c_str(), cpp_file_name, cpp_file_line, ExitGame);
		}

		void WndPopup::Show( const String& msg, bool ExitGame )
		{
			Show(msg.c_str(), ExitGame);
		}

		void WndPopup::Show( StringStream& strm, bool ExitGame )
		{
			String msg(strm.str());
			Show(msg.c_str(), ExitGame);
		}

		void WndPopup::DoPopup( bool ExitGame, std::stringstream& stream )
		{
			SetError(ExitGame);

			if(ExitGame){
				stream<<"\n\n -- 客户端即将关闭";
				::MessageBox(0, stream.str().c_str(), "ERROR", MB_ICONERROR);
				throw std::exception();
			}else{
				::MessageBox(0, stream.str().c_str(), "WARNING", MB_ICONWARNING);
				ResetError();
			}
		}


	}//Debug
}//GLL